﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace TheOliver.Controls
{
	public class DeepZoomSlideShowBehavior : TargetedTriggerAction<MultiScaleImage>
	{
		private MultiScaleImage _msi;
        private int _count = 0;
        private int _totalImages;
		
		protected override void Invoke(object o)
		{
            if (this._msi == null)
            {
                this._msi = this.Target;
                _totalImages = _msi.SubImages.Count;
            }

            if (_count < _totalImages)
            {
                ZoomOnImage(_count);
            }
            else
            {
                _count = 0;
                ZoomOnImage(_count);
            }
		}

        private void ZoomOnImage(int subImageIndex)
        {
            _count++;
            
            MultiScaleSubImage subImage = _msi.SubImages[subImageIndex];

            double scaleBy = 1 / subImage.ViewportWidth;

            Rect subImageRect = 
                new Rect(-subImage.ViewportOrigin.X * scaleBy,
                    -subImage.ViewportOrigin.Y * scaleBy,
                    scaleBy,
                    (1 / subImage.AspectRatio) * scaleBy);

            if ((this._msi.Width / this._msi.Height) > subImage.AspectRatio)
            {
                double targetViewportWidth = subImageRect.Height * this._msi.AspectRatio;
                double targetPointX = (targetViewportWidth - subImageRect.Width) / 2;

                this._msi.ViewportOrigin = new Point(subImageRect.X - targetPointX, subImageRect.Y);
                this._msi.ViewportWidth = targetViewportWidth;
            }
            else
            {
                this._msi.ViewportWidth = subImageRect.Width;
                this._msi.ViewportOrigin = new Point(subImageRect.X, subImageRect.Y);
            }
        }
    }
}